package net.pimpas.web.jsf.renderers.focus.html;

import java.io.IOException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.Renderer;

import org.apache.myfaces.shared_impl.renderkit.html.HTML;

import net.pimpas.logging.serviceprovider.LoggingServiceProvider;
import net.pimpas.logging.serviceprovider.LoggingServiceProviderFactoryImpl;
import net.pimpas.web.jsf.components.focus.UIFocus;
import net.pimpas.web.jsf.util.ComponentUtils;

public class HtmlFocusRenderer extends Renderer {
	
	private static LoggingServiceProvider logger = LoggingServiceProviderFactoryImpl.
	getLoggingServiceProvider(HtmlFocusRenderer.class);
	
	@Override
	public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
		if(!component.isRendered()) return;
		if(!ComponentUtils.isCorrectComponentType(component, UIFocus.class)) return;
		
		UIFocus focus = (UIFocus) component;
		
		// check component
		UIComponent target = ComponentUtils.getComponentById(context.getViewRoot(),
				context, focus.getForComponent(), ComponentUtils.SERVER_ID);
		if(target == null) {
			logger.debug("[HTMLFocusRenderer]: Can't find target element with server id ["+
					focus.getForComponent()+"]");
			return;
		}
		
		ResponseWriter writer = context.getResponseWriter();
		writer.startElement(HTML.SCRIPT_ELEM, component);
		writer.writeAttribute(HTML.SCRIPT_TYPE_ATTR, HTML.SCRIPT_TYPE_TEXT_JAVASCRIPT, null);
		writer.write("pimpas.DOM.focus('"+target.getClientId(context)+"');");
		writer.endElement(HTML.SCRIPT_ELEM);
	}
}
